package controller.ProductController;

import bean.OrderDetails;
import bean.OrderForm;
import bean.Product;
import bean.User;
import com.fasterxml.jackson.databind.ObjectMapper;
import common.AppVariable;
import common.ResultAjax;
import services.ProductService;
import services.impl.ProductServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;

/**
 * @auther hewenhui
 * @see <a href="hetp://www.codingmaster.com> java </a>
 */
@WebServlet("/purchase")
public class PurchaseServlet extends HttpServlet {
    ObjectMapper objectMapper = new ObjectMapper();
    //控制层调用服务层
    ProductService productService = new ProductServiceImpl();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/json; charset=utf-8");
        //判断登录
        HttpSession session = req.getSession(false);
        if(session==null){
            String respJson = objectMapper.writeValueAsString(ResultAjax.fail(-1,"未登录，请先登录！"));
            resp.getWriter().write(respJson);
            return ;
        }
        User user = (User) session.getAttribute(AppVariable.SESSION_USERINFO_KEY);

        // 获取pid
        int pid = Integer.parseInt(req.getParameter("pid"));
        //这就先不判断了

        //根据id查询商品
        Product product = productService.getProductById(pid);
        OrderForm orderForm = new OrderForm();;

        //判断前端cookie是否已经添加了购物车
        // 获取名为 "cart"+user.getUid() 的Cookie数组
        Cookie[] cookies = req.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("cart"+user.getUid())) {
                    String encodedValue = cookie.getValue();
                    String serializedOrderForm = URLDecoder.decode(encodedValue, "UTF-8");
                    // 将序列化的订单对象反序列化为OrderForm对象
                    orderForm = objectMapper.readValue(serializedOrderForm, OrderForm.class);
                    break;
                }
            }
        }

        //创建商品条目
        OrderDetails orderDetails = new OrderDetails(product,1);
        //计算总价格
        orderForm.setPrice(orderForm.getPrice()+orderDetails.getPrice());
        //添加至购物车
        orderForm.getProductsList().add(orderDetails);
        // 将购物车对象序列化为字符串
        String serializedOrderForm = objectMapper.writeValueAsString(orderForm);
        System.out.println("serializedOrderForm"+serializedOrderForm);
        String encodedOrderForm = URLEncoder.encode(serializedOrderForm, "UTF-8");
        // 创建Cookie对象
        Cookie cartCookie = new Cookie("cart"+user.getUid(), encodedOrderForm);

        cartCookie.setPath("/");
        cartCookie.setMaxAge(24 * 60 * 60); // 1天

        // 将Cookie添加到响应中，发送给客户端
        resp.addCookie(cartCookie);

        String respJson = objectMapper.writeValueAsString(ResultAjax.succeed(null));
        resp.getWriter().write(respJson);
        return ;

    }
}
